package repositories

import (
	"gitee.com/cjf8134/bbs_serve/internal/pkg/elastic"
	"gitee.com/cjf8134/bbs_serve/internal/pkg/models"
	"gitee.com/cjf8134/bbs_serve/internal/pkg/requests"
	"gitee.com/cjf8134/bbs_serve/internal/pkg/utils/constutil"
	"github.com/jinzhu/gorm"
	"go.uber.org/zap"
)

// Search  帖子列表
func (r *MysqlApiServeRepository) Search(req *requests.ThreadSearch) (count int64, threadList []*models.Thread, err error) {
	model := r.db.Model(models.Thread{})
	order := "id desc"
	if req.Title != "" {
		model = model.Where("title LIKE ?", "%"+req.Title+"%")
	}
	if req.Limit <= 0 {
		req.Limit = constutil.DefaultPageSize
	}
	if req.Limit > constutil.DefaultMaxPageSize {
		req.Limit = constutil.DefaultMaxPageSize
	}
	req.Page = req.Page - 1
	if req.Page <= 0 {
		req.Page = 0
	}
	model.Count(&count)
	err = model.Preload("Comment", func(db *gorm.DB) *gorm.DB {
		return db.Order("id DESC")
	}).
		Offset(req.Page * req.Limit).Order(order).Limit(req.Limit).Find(&threadList).Error
	return
}

// EsSearch  帖子列表
func (r *MysqlApiServeRepository) EsSearch(req *requests.ThreadSearch) (count int64, threadList []*models.Thread, err error) {
	threadEs, err := elastic.NewThreadES(r.esClient)
	if err != nil {
		return
	}
	threadEsList, err := threadEs.Search(req)
	if err != nil {
		return
	}
	r.logger.Info("threadEsList = ", zap.Any("threadEsList", threadEsList))
	if len(threadEsList) == 0 {
		return
	}
	var ids []string
	for _,index := range threadEsList {
		ids = append(ids,index.ID)
	}
	if len(ids) == 0 {
		return
	}
	err = r.db.Model(models.Thread{}).Where("id in (?)",ids).Find(&threadList).Error
	return
}

